package com.om.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import com.om.db.ConfDB;


public class DataManager {
	private static DataManager _instance = null;
	private static ConfDB conf;
	private final ArrayList<ArrayList<QuestionDS>> all = new ArrayList<ArrayList<QuestionDS>>(5);
	private CONSTANTS.QUESTION_TYPE quizType;
	private static Context context;
	private Quiz currentQuiz = null;
	
    public static synchronized DataManager getInstance() {
        if (_instance == null) {
                _instance = new DataManager();
        }
        return _instance;
}
	
	public static void setContext(Context contextIn) {
		context = contextIn;
	}
	
	public DataManager() {		
		conf = new ConfDB(context);
	}
	
	public void initQuestions(){
		conf.getAllQuestions(all);
	}
	
	public Quiz prepareQuiz(){
		//by type sort 
		ArrayList<QuestionDS>  forQuiz = all.get(quizType.ordinal());
		currentQuiz = new Quiz();
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		int numOfQuestions = Math.min(CONSTANTS.QUESTIONS_NUM_PER_QUIZ, forQuiz.size());
		for (int i=0;i<numOfQuestions;++i) {
			int rand = (int) (Math.random()*forQuiz.size());
			while (map.get(rand) != null) {
				rand = (int) (Math.random()*forQuiz.size());	
			}
			map.put(rand, 1);
			currentQuiz.addQestionDS(forQuiz.get(rand));
		}
		return currentQuiz;
	}
	
	public void onDestroy(){
		conf.onDestroy();
	}
	
	//called when the game is over
	public void updateQuestionWereFetched() {		
	}

	public void setQuestionType(String btnName) {
		btnName = btnName.substring(btnName.length()-1, btnName.length());
		int i = Integer.valueOf(btnName);
		quizType = CONSTANTS.QUESTION_TYPE.values()[i-1];	
	}
	
	public CONSTANTS.QUESTION_TYPE getQuestionType(){
		return quizType;
	}
	
	public String getQuestionTypeStr(){
		String str = null;
		switch (quizType) {
			case OLYMPIC_GAMES:
				str = "History";
				break;
			case COUNTRIES:
				str = "Countries";
				break;
			case ATHLETES:
				str = "Athletes";
				break;				
			case EXTRA:
				str = "Bonus";
				break;
			case LONDON:
				str = "London 2012";
				break;			
		} 
		return str;		
	}
	
	public Quiz getCurrentQuiz(){
		return currentQuiz;
	}

}
